import { create } from "zustand";
import { persist } from "zustand/middleware";
import { routeConfig } from "../config/routes";

// 从路由配置生成标签页配置
const getTabConfigFromRoute = (path) => {
  const route = routeConfig.find((r) => r.path === path);
  if (!route) return null;

  return {
    key: path.substring(1) || "dashboard", // 移除开头的 '/'
    title: route.meta?.title, // 保持原始标题（可能是i18n key）
    icon: getIconName(route.meta?.icon), // 转换为字符串名称
    closable: path !== "/dashboard", // 仪表板不可关闭
  };
};

// 将React图标组件转换为字符串名称（用于TabBar显示）
const getIconName = (iconComponent) => {
  if (!iconComponent) return "DashboardOutlined";

  // 直接使用图标组件的 displayName，确保与路由中的图标完全一致
  if (iconComponent?.type?.displayName) {
    return iconComponent.type.displayName;
  }

  // 后备方案：通过字符串匹配
  const componentString = iconComponent.toString();
  if (componentString.includes("Environment")) return "EnvironmentOutlined";
  if (componentString.includes("Setting")) return "SettingOutlined";
  if (componentString.includes("Database")) return "DatabaseOutlined";
  if (componentString.includes("Bulb")) return "BulbOutlined";
  if (componentString.includes("Dashboard")) return "DashboardOutlined";
  if (componentString.includes("Swap")) return "SwapOutlined";

  return "DashboardOutlined"; // 默认图标
};

const useTabStore = create(
  persist(
    (set, get) => ({
      // 当前打开的标签页列表
      tabs: [
        {
          key: "dashboard",
          path: "/dashboard",
          title: "仪表盘",
          icon: "DashboardOutlined",
          closable: false,
        },
      ],

      // 当前激活的标签页
      activeTab: "dashboard",

      // 标签页历史记录（用于智能排序）
      tabHistory: ["dashboard"],

      // 最大标签页数量
      maxTabs: 10,

      // 标记是否正在关闭标签页（防止自动添加）
      isClosingTab: false,

      // 关闭标签页的时间戳（防止短时间内重复添加）
      lastCloseTime: 0,

      // 添加新标签页
      addTab: (path, options = {}) => {
        const { isClosingTab, lastCloseTime } = get();

        // 如果刚刚关闭了标签页，短时间内阻止自动添加
        const now = Date.now();
        if (isClosingTab || now - lastCloseTime < 500) {
          // 500ms 内阻止自动添加
          console.log(`阻止自动添加标签页: ${path} (刚关闭了其他标签页)`);
          return;
        }

        const config = getTabConfigFromRoute(path);
        if (!config) return;

        const { tabs, maxTabs } = get();
        const existingTab = tabs.find((tab) => tab.path === path);

        // 如果标签页已存在，直接激活
        if (existingTab) {
          set((state) => ({
            activeTab: existingTab.key,
            tabHistory: [
              existingTab.key,
              ...state.tabHistory.filter((k) => k !== existingTab.key),
            ],
          }));
          return;
        }

        // 如果超过最大数量，关闭最旧的可关闭标签页
        let newTabs = [...tabs];
        if (newTabs.length >= maxTabs) {
          const { tabHistory } = get();
          for (let i = tabHistory.length - 1; i >= 0; i--) {
            const tabToClose = newTabs.find((tab) => tab.key === tabHistory[i]);
            if (tabToClose && tabToClose.closable) {
              newTabs = newTabs.filter((tab) => tab.key !== tabToClose.key);
              break;
            }
          }
        }

        // 创建新标签页
        const newTab = {
          key: config.key,
          path,
          title: options.title || config.title,
          icon: config.icon,
          closable: config.closable,
          ...options,
        };

        set((state) => ({
          tabs: [...newTabs, newTab],
          activeTab: newTab.key,
          tabHistory: [
            newTab.key,
            ...state.tabHistory.filter((k) => k !== newTab.key),
          ],
        }));
      },

      // 关闭标签页
      closeTab: (tabKey) => {
        const { tabs, activeTab, tabHistory } = get();
        const targetTab = tabs.find((tab) => tab.key === tabKey);

        // 不可关闭的标签页不能关闭
        if (!targetTab || !targetTab.closable) {
          console.warn(`标签页 ${tabKey} 不可关闭或不存在`);
          return null;
        }

        const newTabs = tabs.filter((tab) => tab.key !== tabKey);
        let newActiveTab = activeTab;
        let newHistory = tabHistory.filter((k) => k !== tabKey);

        // 如果关闭的是当前激活标签页，需要切换到其他标签页
        if (activeTab === tabKey) {
          // 智能选择下一个标签页，避免在演示页面之间循环
          let nextTab = null;

          // 1. 优先从历史记录中选择非演示页面
          const nonDemoTabs = newTabs.filter(
            (tab) => !tab.path.includes("demo") && tab.key !== "dashboard"
          );
          if (nonDemoTabs.length > 0) {
            nextTab = newHistory.find((key) =>
              nonDemoTabs.some((tab) => tab.key === key)
            );
          }

          // 2. 如果没有找到，选择最近访问的非演示页面
          if (!nextTab && nonDemoTabs.length > 0) {
            nextTab = nonDemoTabs[nonDemoTabs.length - 1].key;
          }

          // 3. 如果没有非演示页面，回退到历史记录或仪表板
          if (!nextTab) {
            nextTab = newHistory.find((key) =>
              newTabs.some((tab) => tab.key === key)
            );
          }

          newActiveTab = nextTab || "dashboard";
        }

        console.log(
          `关闭标签页: ${tabKey}, 剩余标签页:`,
          newTabs.map((t) => t.key)
        );

        // 设置关闭标签页的标记和时间戳
        set({
          tabs: newTabs,
          activeTab: newActiveTab,
          tabHistory: newHistory,
          isClosingTab: true,
          lastCloseTime: Date.now(),
        });

        // 500ms 后清除关闭标记
        setTimeout(() => {
          set({ isClosingTab: false });
        }, 500);

        return (
          newTabs.find((tab) => tab.key === newActiveTab)?.path || "/dashboard"
        );
      },

      // 关闭其他标签页
      closeOtherTabs: (keepTabKey) => {
        const { tabs } = get();
        const keepTab = tabs.find((tab) => tab.key === keepTabKey);
        const dashboardTab = tabs.find((tab) => tab.key === "dashboard");

        const newTabs = [dashboardTab, keepTab].filter(Boolean);
        const uniqueTabs = newTabs.filter(
          (tab, index, self) =>
            index === self.findIndex((t) => t.key === tab.key)
        );

        set({
          tabs: uniqueTabs,
          activeTab: keepTabKey,
          tabHistory: [keepTabKey, "dashboard"],
        });
      },

      // 关闭所有可关闭的标签页
      closeAllTabs: () => {
        const { tabs } = get();
        const newTabs = tabs.filter((tab) => !tab.closable);

        set({
          tabs: newTabs,
          activeTab: "dashboard",
          tabHistory: ["dashboard"],
        });
      },

      // 切换标签页
      switchTab: (tabKey) => {
        const { tabs } = get();
        const targetTab = tabs.find((tab) => tab.key === tabKey);
        if (!targetTab) return;

        set((state) => ({
          activeTab: tabKey,
          tabHistory: [tabKey, ...state.tabHistory.filter((k) => k !== tabKey)],
        }));

        return targetTab.path;
      },

      // 更新标签页信息
      updateTab: (tabKey, updates) => {
        set((state) => ({
          tabs: state.tabs.map((tab) =>
            tab.key === tabKey ? { ...tab, ...updates } : tab
          ),
        }));
      },

      // 获取标签页配置
      getTabConfig: (path) => getTabConfigFromRoute(path),

      // 重新排序标签页
      reorderTabs: (newTabs) => {
        set({ tabs: newTabs });
      },

      // 重置所有标签页（清理可能的错误状态）
      resetTabs: () => {
        const dashboardConfig = getTabConfigFromRoute("/dashboard");
        set({
          tabs: [
            {
              ...dashboardConfig,
              path: "/dashboard",
            },
          ],
          activeTab: "dashboard",
          tabHistory: ["dashboard"],
          isClosingTab: false,
          lastCloseTime: 0,
        });
        console.log("标签页状态已重置");
      },

      // 调试方法：打印当前状态
      debugTabs: () => {
        const { tabs, activeTab } = get();
        console.log("当前标签页状态:", {
          tabs: tabs.map((t) => ({
            key: t.key,
            path: t.path,
            closable: t.closable,
          })),
          activeTab,
        });
      },

      // 清空所有状态（用于登出等场景）
      clearTabs: () => {
        const dashboardConfig = getTabConfigFromRoute("/dashboard");
        set({
          tabs: [
            {
              ...dashboardConfig,
              path: "/dashboard",
            },
          ],
          activeTab: "dashboard",
          tabHistory: ["dashboard"],
          isClosingTab: false,
          lastCloseTime: 0,
        });
      },
    }),
    {
      name: "tab-store",
      partialize: (state) => ({
        tabs: state.tabs,
        activeTab: state.activeTab,
        tabHistory: state.tabHistory,
      }),
    }
  )
);

export default useTabStore;
